import { getDataByDate, getDataByDateRange } from "../../api/move";
import { handleCalendar } from "../../hooks/interface"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    year: 0,
    month: 0,
    day: 0,
    current: {} as Current,
    weeks: [] as Week[],
    isToday: true,
    touchDotX: 0, //X按下时坐标
    touchDotY: 0, //Y按下时坐标
    interval: null as number | null,
    time: 0 as number,
    animationData: {},
    showLoading: true as boolean,
    dayData: [] as { [key: number]: FormData[][] },//接口返回的数据
    key: [] as Array<string>,//area的长度
    navItem: [] as NavItem[],
    timer: null as null | number
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    const date = new Date();
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    this.setData({
      year: this.options.year ? Number(this.options.year) : year,
      month: this.options.month ? Number(this.options.month) : month,
      day: this.options.day ? Number(this.options.day) : day,
      current: {
        today: day,
        month,
        year
      },
      currentMonth: month
    })
    this.getDate();
    this.getDataByDate();
    this.getNavItem();
    this.data.timer = setTimeout(() => {
      this.setData({
        showLoading: false
      })
    }, 1000)
  },
  // 获取一个月几天
  getDaysInMonth(year: number, month: number): number {
    if (month <= 0) {
      month = 12;
      year = year - 1
    } else if (month > 12) {
      month = 1
      year = year + 1
    }
    // 在 JavaScript 中，Date 的月份是从 0 开始的，所以需要 -1
    return new Date(year, month, 0).getDate();
  },
  // 获取一个月第一天是周几
  getFirstDayOfMonth(year: number, month: number): number {
    if (month <= 0) {
      month = 12;
      year = year - 1
    } else if (month > 12) {
      month = 1
      year = year + 1
    }
    return new Date(this.data.year, this.data.month - 1, 1).getDay();
  },
  // 切换到下个月
  toNextMonth(): void {
    let month = this.data.month + 1;
    let year = this.data.year
    if (month > 12) {
      month = 1;
      year += 1;
    }
    this.setData({
      month,
      year
    })
    this.getDate();
    this.getDataByDate();
  },
  // 切换到上个月
  toPreMonth(): void {
    let month = this.data.month - 1;
    let year = this.data.year
    if (month <= 0) {
      month = 12;
      year -= 1;
    }
    this.setData({
      month,
      year
    })
    this.getDate();
    this.getDataByDate();
  },
  // 封装获取这月信息的代码
  getDate(): void {
    // 统一处理是不是今天，返回给组件进行展示
    if (this.data.current.today === this.data.day && this.data.current.month === this.data.month && this.data.current.year === this.data.year) {
      this.setData({
        isToday: true
      })
    } else {
      this.setData({
        isToday: false
      })
    }

    // 这个月多少天
    const daysInMonth = this.getDaysInMonth(this.data.year, this.data.month);
    // 当前日期31号，如果左右切换时，没有31号的月份需要单独处理
    if (this.data.day > daysInMonth) {
      this.setData({
        day: daysInMonth
      })
    }
    // 这个月第一天是周几
    let firstDay = this.getFirstDayOfMonth(this.data.year, this.data.month);
    // 如果每个月第一天是周日，返回为0，需要处理成7
    if (!firstDay) {
      firstDay = 7;
    }

    // 获取上个月的最后一天
    const daysInLastMonth = this.getDaysInMonth(this.data.year, this.data.month - 1);
    const weeks = [];
    let week: Day[] = [];
    let dayOfWeek = firstDay;

    // 上个月空几格，往前找几天
    for (let i = 1; i < firstDay; i++) {
      week[i - 1] = { value: daysInLastMonth - firstDay + i + 1, isCurrentMonth: "pre", year: this.data.month - 1 == 0 ? this.data.year - 1 : this.data.year, month: this.data.month - 1 == 0 ? 12 : this.data.month - 1 };
    }

    for (let day = 1; day <= daysInMonth; day++) {
      // 从一号开始存，value代表是几号
      week[dayOfWeek - 1] = { value: day, isCurrentMonth: "cur", year: this.data.year, month: this.data.month };
      // 每个week存7天，如果dayOfWeek === 7 或者到最后一天了，存进去(最后一周没满先不存进去，把下个月后面几天加进去再存)
      if (dayOfWeek === 7) {
        weeks.push({ days: week });
        week = [];
        dayOfWeek = 0;
      }
      dayOfWeek++;
    }
    // 如果最后一个周没有满，就用下个月的前几天来填充
    if (week.length > 0) {
      for (let day = 1; week.length < 7; day++) {
        week.push({
          value: day,
          isCurrentMonth: "next",
          year: this.data.month + 1 == 13 ? this.data.year + 1 : this.data.year,
          month: this.data.month + 1 == 13 ? 1 : this.data.month + 1
        });
      }
      weeks.push({ days: week });
    }
    this.setData({
      weeks
    });
    this.checkDataAvailability(daysInMonth);
  },
  // 自定义事件
  changeCalendar(e: any): void {
    this.setData({
      day: e.detail.value
    })
    if (e.detail.isCurrentMonth === "pre") {
      this.toPreMonth();
    } else if (e.detail.isCurrentMonth === "next") {
      this.toNextMonth();
    } else {
      this.getDataByDate();
      if (this.data.current.today === this.data.day && this.data.current.month === this.data.month && this.data.current.year === this.data.year) {
        this.setData({
          isToday: true
        })
      } else {
        this.setData({
          isToday: false
        })
      }
    }

  },
  toToday(): any {
    this.onLoad();
  },
  // 开始移动
  touchStart(e: any): void {
    this.data.touchDotX = e.touches[0].pageX; // 获取触摸时的原点
    this.data.touchDotY = e.touches[0].pageY;
    // 使用js计时器记录时间    
    this.data.interval = setInterval(() => {
      this.data.time++;
    }, 1);
  },
  // 结束移动
  touchEnd(e: any): void {
    const touchMoveX = e.changedTouches[0].pageX;
    const touchMoveY = e.changedTouches[0].pageY;
    const tmX = touchMoveX - this.data.touchDotX;
    const tmY = touchMoveY - this.data.touchDotY;
    if (this.data.time < 20) {
      const absX = Math.abs(tmX);
      const absY = Math.abs(tmY);
      if (absX > 2 * absY) {
        if (tmX < 0) {
          console.log("左滑=====");
          // this.swipeLeft();
          this.toNextMonth();
        } else {
          console.log("右滑=====");
          // this.swipeRight();
          this.toPreMonth();
        }
      }
    }
    this.data.touchDotX = 0;
    this.data.touchDotY = 0;
    if (this.data.interval !== null) {
      clearInterval(this.data.interval);
    }
    this.data.interval = null;
    this.data.time = 0
  },
  swipeLeft(): void {
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease',
    })

    animation.translateX(-100).step() // 这里的-100需要你根据日历的宽度来调整

    this.setData({
      animationData: animation.export()
    })

    setTimeout(() => {
      animation.translateX(0).step()
      this.setData({
        animationData: animation.export(),
        // 这里你需要更新日历的数据，例如切换到下一个月
      })
    }, 500)
  },

  swipeRight: function () {
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease',
    })

    animation.translateX(600).step() // 这里的100需要你根据日历的宽度来调整

    this.setData({
      animationData: animation.export()
    })

    setTimeout(() => {
      animation.translateX(0).step()
      this.setData({
        animationData: animation.export(),
        // 这里你需要更新日历的数据，例如切换到上一个月
      })
    }, 500)
  },

  // 获取数据
  getDataByDate() {
    const params = [this.data.year, this.data.month.toString().padStart(2,'0'), this.data.day.toString().padStart(2,'0')].join("-")
    getDataByDate(params).then((res: Response) => {
      const dayData = handleCalendar(res.data);
      const key = Object.keys(dayData);
      this.setData({
        dayData,
        key
      })
    })
  },
  onUnload() {
    this.setData({
      timer: null
    })
  },
  toChoose(): void {
    wx.navigateTo({
      url: `/pages/activity/activity?year=${this.data.year}&month=${this.data.month}&day=${this.data.day}`,
    })
  },
  getNavItem(): void {
    const app = getApp<IAppOption>();
    this.setData({
      navItem: app.globalData.exerciseArea
    })
  },
  async checkDataAvailability(daysInMonth: number): Promise<void> {
    const dateRanges: DateRange[] = [];
    // 处理上个月
    if (this.data.weeks[0].days[0].isCurrentMonth === 'pre') {
      // 获取上个月最后一天
      const lastDayOfLastMonth = this.getDaysInMonth(this.data.year, this.data.month - 1);

      // 请求上个月的最后几天数据
      const startDateOfLastMonth = this.data.weeks[0].days.find(day => day.isCurrentMonth === 'pre')!.value;
      const endDateOfLastMonth = lastDayOfLastMonth;
      dateRanges.push({
        year: this.data.year,
        month: this.data.month == 1 ? 12 : this.data.month - 1,
        startDate: startDateOfLastMonth,
        endDate: endDateOfLastMonth,
      });
    }
    // 处理当前月
    dateRanges.push({
      year: this.data.year,
      month: this.data.month,
      startDate: 1,
      endDate: daysInMonth
    });
    // 处理下个月的日期范围
    if (this.data.weeks[this.data.weeks.length - 1].days[this.data.weeks[this.data.weeks.length - 1].days.length - 1].isCurrentMonth === 'next') {
      dateRanges.push({
        year: this.data.year,
        month: this.data.month == 12 ? 1 : this.data.month + 1,
        startDate: 1,
        endDate: this.data.weeks[this.data.weeks.length - 1].days[this.data.weeks[this.data.weeks.length - 1].days.length - 1].value
      });
    }
    // 异步处理每个日期范围的数据请求
    const promises = dateRanges.map(async (range: DateRange) => {
      // 变成字符串
      const startDate = range.year + "-" + range.month.toString().padStart(2, '0') + "-" + range.startDate.toString().padStart(2, '0')
      const endDate = range.year + "-" + range.month.toString().padStart(2, '0') + "-" + range.endDate.toString().padStart(2, '0')
      return this.fetchDateAvailability(startDate, endDate);
    });
    // 等待所有请求完成
    const responses: Response[] = await Promise.all(promises);
    console.log(responses);

    // 将响应结果合并到weeks的days中
    // let temp = "";
    // responses.map((response, index) => {
    //   this.data.weeks.map(item => {
    //     temp = item.days[0].isCurrentMonth
    //     item.days.map(day => {
    //       if(day.isCurrentMonth !== temp) {
    //         return;
    //       }
    //       if(response.data.includes(day.value)) {
    //         day.hasData = true;
    //       }else {
    //         day.hasData = false;
    //       }
    //     })
    //   })
    // });
    let currentIndex = 0;
    let currentMonth = '';

    this.data.weeks.forEach(item => {
      item.days.forEach(day => {
        if (day.isCurrentMonth !== currentMonth) {
          currentMonth = day.isCurrentMonth;
          currentIndex++;
        }
        const responseToCheck = responses[currentIndex - 1];
        if (responseToCheck.data && responseToCheck.data.includes(day.value.toString().padStart(2, '0'))) {
          day.hasData = true;
        } else {
          day.hasData = false;
        }
      });
    });

    // 更新视图数据
    this.setData({
      weeks: this.data.weeks
    });
  },
  // 获取范围内的数据
  async fetchDateAvailability(startDate: string, endDate: string): Promise<Response> {
    const response = await getDataByDateRange(startDate, endDate);
    return response;
  },
  onShow() {
    this.getDataByDate();
  }
})